package com.baozhun.mall.common.widget.dialog

import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.widget.LinearLayout
import android.widget.TextView
import com.baozhun.mall.common.R
import com.contrarywind.view.WheelView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import com.lxj.xpopupext.view.WheelTime
import java.text.ParseException
import java.util.Calendar
/**
 * @Title：
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2023/12/20
 * @Version：1.0.0
 */
open class TimePickerPopup(context: Context) : BottomPopupView(context) {
    enum class Mode {
        YMDHMS, YMDHM, YMDH, YMD, YM, Y
    }

    var timePickerListener: TimePickerListener? = null
    private var mode = TimePickerPopup.Mode.YMD
    private var isLunar = false //是否是农历
    private var startYear = 0
    private var endYear = 0
    private var itemsVisibleCount = 7
    private var itemTextSize = 16
    private var date = Calendar.getInstance()
    private var startDate: Calendar? = null
    private var endDate: Calendar? = null
    var dividerColor = -0x2a2a2b //分割线的颜色
    var lineSpace = 2.8f // 条目间距倍数 默认2
    var textColorOut = -0x575758 //分割线以外的文字颜色
    var textColorCenter = -0xd5d5d6 //分割线之间的文字颜色
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_brith_day_choose
    }

    private var wheelTime: WheelTime? = null //自定义控件
    fun mode2type(): BooleanArray {
        return when (mode) {
            TimePickerPopup.Mode.Y -> booleanArrayOf(true, false, false, false, false, false)
            TimePickerPopup.Mode.YM -> booleanArrayOf(true, true, false, false, false, false)
            TimePickerPopup.Mode.YMD -> booleanArrayOf(true, true, true, false, false, false)
            TimePickerPopup.Mode.YMDH -> booleanArrayOf(true, true, true, true, false, false)
            TimePickerPopup.Mode.YMDHM -> booleanArrayOf(true, true, true, true, true, false)
            else -> booleanArrayOf(true, true, true, true, true, true)
        }
    }

    var btnCancel: TextView? = null
    var btnConfirm: TextView? = null
    override fun onCreate() {
        super.onCreate()
        btnCancel = findViewById(R.id.btnCancel)
        btnConfirm = findViewById(R.id.btnConfirm)
        btnCancel?.setOnClickListener(OnClickListener {
            if (timePickerListener != null) timePickerListener!!.onCancel()
            dismiss()
        })
        btnConfirm?.setTextColor(XPopup.getPrimaryColor())
        btnConfirm?.setOnClickListener(OnClickListener { v ->
            if (timePickerListener != null) {
                try {
                    val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                    timePickerListener!!.onTimeConfirm(date, v)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
            dismiss()
        })
        initWheelTime(findViewById<View>(R.id.timepicker) as LinearLayout)
        if (popupInfo.isDarkTheme) {
            applyDarkTheme()
        } else {
            applyLightTheme()
        }
    }

    override fun applyDarkTheme() {
        super.applyDarkTheme()
        btnCancel!!.setTextColor(Color.parseColor("#999999"))
        btnConfirm!!.setTextColor(Color.parseColor("#ffffff"))
        popupImplView.background = XPopupUtils.createDrawable(
            resources.getColor(com.lxj.xpopup.R.color._xpopup_dark_color),
            popupInfo.borderRadius, popupInfo.borderRadius, 0f, 0f
        )
    }

    override fun applyLightTheme() {
        super.applyLightTheme()
        btnCancel!!.setTextColor(Color.parseColor("#666666"))
        btnConfirm!!.setTextColor(Color.parseColor("#222222"))
        popupImplView.background = XPopupUtils.createDrawable(
            resources.getColor(com.lxj.xpopup.R.color._xpopup_light_color),
            popupInfo.borderRadius, popupInfo.borderRadius, 0f, 0f
        )
    }

    private fun initWheelTime(timePickerView: LinearLayout) {
        wheelTime = WheelTime(timePickerView, mode2type(), Gravity.CENTER, itemTextSize)
        if (timePickerListener != null) {
            wheelTime!!.setSelectChangeCallback {
                try {
                    val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                    timePickerListener!!.onTimeChanged(date)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
        }
        wheelTime!!.isLunarMode = isLunar
        if (startYear != 0 && endYear != 0 && startYear <= endYear) {
            applyYear()
        }

        //若手动设置了时间范围限制
        if (startDate != null && endDate != null) {
            require(startDate!!.timeInMillis <= endDate!!.timeInMillis) { "startDate can't be later than endDate" }
            applyDateRange()
        } else if (startDate != null) {
            require(startDate!![Calendar.YEAR] >= 1900) { "The startDate can not as early as 1900" }
            applyDateRange()
        } else if (endDate != null) {
            require(endDate!![Calendar.YEAR] <= 2100) { "The endDate should not be later than 2100" }
            applyDateRange()
        } else { //没有设置时间范围限制，则会使用默认范围。
            applyDateRange()
        }
        setTime()
        if (showLabel) wheelTime!!.setLabels(
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_year),
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_month),
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_day),
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_hours),
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_minutes),
            resources.getString(com.lxj.xpopupext.R.string._xpopup_ext_seconds)
        )
        wheelTime!!.setItemsVisible(itemsVisibleCount)
        wheelTime!!.setAlphaGradient(true)
        wheelTime!!.setCyclic(false)
        wheelTime!!.setDividerColor(if (popupInfo.isDarkTheme) Color.parseColor("#444444") else dividerColor)
        wheelTime!!.setDividerType(WheelView.DividerType.FILL)
        wheelTime!!.setLineSpacingMultiplier(lineSpace)
        wheelTime!!.setTextColorOut(textColorOut)
        wheelTime!!.setTextColorCenter(if (popupInfo.isDarkTheme) Color.parseColor("#CCCCCC") else textColorCenter)
        wheelTime!!.isCenterLabel(false)
    }

    var showLabel = true

    /**
     * 是否显示年月日字样
     * @return
     */
    fun setShowLabel(showLabel: Boolean): com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.showLabel = showLabel
        return this
    }

    fun setTimePickerListener(listener: TimePickerListener?): com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        timePickerListener = listener
        return this
    }

    fun setItemTextSize(textSize: Int):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        itemTextSize = textSize
        return this
    }

    fun setMode(mode: TimePickerPopup.Mode):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.mode = mode
        return this
    }

    /**
     * 是否是农历
     * @param isLunar
     * @return
     */
    fun setLunar(isLunar: Boolean):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.isLunar = isLunar
        return this
    }

    fun setItemsVisibleCount(itemsVisibleCount: Int):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.itemsVisibleCount = itemsVisibleCount
        return this
    }

    fun setLineSpace(lineSpace: Float):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.lineSpace = lineSpace
        return this
    }

    /**
     * 设置默认时间
     */
    fun setDefaultDate(date: Calendar?):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.date = date
        return this
    }

    /**
     * 设置年份范围
     */
    fun setYearRange(startYear: Int, endYear: Int):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.startYear = startYear
        this.endYear = endYear
        return this
    }

    /**
     * 设置可以选择的时间范围
     */
    fun setDateRange(startDate: Calendar?, endDate: Calendar?):  com.baozhun.mall.common.widget.dialog.TimePickerPopup {
        this.startDate = startDate
        this.endDate = endDate
        return this
    }

    private fun applyYear() {
        wheelTime!!.startYear = startYear
        wheelTime!!.endYear = endYear
    }

    private fun applyDateRange() {
        wheelTime!!.setRangDate(startDate, endDate)
        initDefaultSelectedDate()
    }

    private fun initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (startDate != null && endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (date == null || date.timeInMillis < startDate!!.timeInMillis || date.timeInMillis > endDate!!.timeInMillis) {
                date = startDate
            }
        } else if (startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            date = startDate
        } else if (endDate != null) {
            date = endDate
        }
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private fun setTime() {
        val year: Int
        val month: Int
        val day: Int
        val hours: Int
        val minute: Int
        val seconds: Int
        val calendar = Calendar.getInstance()
        if (date == null) {
            calendar.timeInMillis = System.currentTimeMillis()
            year = calendar[Calendar.YEAR]
            month = calendar[Calendar.MONTH]
            day = calendar[Calendar.DAY_OF_MONTH]
            hours = calendar[Calendar.HOUR_OF_DAY]
            minute = calendar[Calendar.MINUTE]
            seconds = calendar[Calendar.SECOND]
        } else {
            year = date[Calendar.YEAR]
            month = date[Calendar.MONTH]
            day = date[Calendar.DAY_OF_MONTH]
            hours = date[Calendar.HOUR_OF_DAY]
            minute = date[Calendar.MINUTE]
            seconds = date[Calendar.SECOND]
        }
        wheelTime!!.setPicker(year, month, day, hours, minute, seconds)
    }
}